package com.xmg.p2p.base.service.impl;

import com.xmg.p2p.base.service.IMailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
@Service
public class MailServiceImpl implements IMailService{
    @Value("${mail.host}")
    private String host;
    @Value("${mail.username}")
    private String username;
    @Value("${mail.password}")
    private String password;
    @Override
    public void sendMail(String target, String title, String content) {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(host);
        MimeMessage message = sender.createMimeMessage();
        // 创建一个邮件助手
        MimeMessageHelper helper = new MimeMessageHelper(message,"UTF-8");
        try {
            helper.setTo(target);
            helper.setFrom(username,"管理员");
            helper.setSubject(title);
            helper.setText(content,true);
            sender.setUsername(username);
            sender.setPassword(password);
            Properties prop = new Properties();
            prop.put("mail.smtp.auth", "true");// 设置发送邮件需要身份认证
            prop.put("mail.smtp.timeout", "25000");// 设置发送超时时间
            sender.setJavaMailProperties(prop);
            sender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发送邮件失败");
        }

    }
}
